# -*- coding: utf-8 -*-

import uuid
import base64
from odoo import models, fields, api


class FileUpload(models.Model):
    _name = 'file.upload'
    _description = '文件上传'
    _inherit = ['mail.thread', 'mail.activity.mixin']
    _order = 'create_date desc'

    name = fields.Char(string='文件名', required=True, tracking=True)
    file_data = fields.Binary(string='文件', required=True, attachment=True)
    file_size = fields.Integer(string='文件大小 (字节)', compute='_compute_file_size', store=True)
    file_type = fields.Char(string='文件类型')
    description = fields.Text(string='描述')
    
    # 唯一下载令牌
    download_token = fields.Char(string='下载令牌', default=lambda self: str(uuid.uuid4()), 
                                  required=True, readonly=True, copy=False, index=True)
    
    # 下载链接
    download_url = fields.Char(string='下载链接', compute='_compute_download_url', store=False)
    
    # 统计信息
    download_count = fields.Integer(string='下载次数', default=0, readonly=True)
    last_download_date = fields.Datetime(string='最后下载时间', readonly=True)
    
    # 访问控制
    is_public = fields.Boolean(string='公开访问', default=True, tracking=True)
    expiry_date = fields.Datetime(string='过期时间', tracking=True)
    is_expired = fields.Boolean(string='已过期', compute='_compute_is_expired', store=True)
    
    # 用户信息
    user_id = fields.Many2one('res.users', string='上传用户', 
                              default=lambda self: self.env.user, readonly=True)
    company_id = fields.Many2one('res.company', string='公司',
                                 default=lambda self: self.env.company)
    
    active = fields.Boolean(string='启用', default=True)

    @api.depends('file_data')
    def _compute_file_size(self):
        """计算文件大小"""
        for record in self:
            if record.file_data:
                try:
                    # 处理可能的 padding 问题
                    file_data_str = record.file_data
                    if isinstance(file_data_str, bytes):
                        file_data_str = file_data_str.decode('utf-8')
                    record.file_size = len(base64.b64decode(file_data_str))
                except Exception:
                    # 如果解码失败（包括 binascii.Error），设置为 0
                    record.file_size = 0
            else:
                record.file_size = 0

    @api.depends('download_token')
    def _compute_download_url(self):
        """生成下载链接"""
        # 获取基础 URL，优先使用配置的域名
        base_url = self.env['ir.config_parameter'].sudo().get_param('web.base.url')
        
        # 如果 base_url 是 localhost 或内部地址，尝试使用请求头中的域名
        if not base_url or 'localhost' in base_url or base_url.startswith('http://odoo'):
            try:
                request = self.env.context.get('request')
                if request and hasattr(request, 'httprequest'):
                    # 尝试从请求头获取真实域名
                    host = request.httprequest.headers.get('X-Forwarded-Host') or \
                           request.httprequest.headers.get('Host', '')
                    proto = request.httprequest.headers.get('X-Forwarded-Proto', 'https')
                    if host:
                        base_url = f"{proto}://{host}"
            except:
                pass
        
        # 如果仍然没有有效的 base_url，使用默认值
        if not base_url or base_url.startswith('http://odoo'):
            base_url = 'https://naturedao.tech'
        
        for record in self:
            if record.download_token:
                record.download_url = f"{base_url}/file/download/{record.download_token}"
            else:
                record.download_url = False

    @api.depends('expiry_date')
    def _compute_is_expired(self):
        """检查是否过期"""
        now = fields.Datetime.now()
        for record in self:
            if record.expiry_date:
                record.is_expired = record.expiry_date < now
            else:
                record.is_expired = False

    def action_regenerate_token(self):
        """重新生成下载令牌"""
        for record in self:
            record.download_token = str(uuid.uuid4())
            record.message_post(body='下载令牌已重新生成')

    def action_copy_download_link(self):
        """显示下载链接"""
        self.ensure_one()
        return {
            'type': 'ir.actions.client',
            'tag': 'display_notification',
            'params': {
                'title': '下载链接',
                'message': f'请复制此链接: {self.download_url}',
                'type': 'success',
                'sticky': True,
            }
        }

    def increment_download_count(self):
        """增加下载计数"""
        self.sudo().write({
            'download_count': self.download_count + 1,
            'last_download_date': fields.Datetime.now()
        })

    @api.model
    def get_file_by_token(self, token):
        """通过令牌获取文件（公开访问）"""
        file_record = self.sudo().search([('download_token', '=', token)], limit=1)
        if not file_record:
            return None
        
        # 检查是否启用
        if not file_record.active:
            return None
        
        # 检查是否公开
        if not file_record.is_public:
            return None
        
        # 检查是否过期
        if file_record.is_expired:
            return None
        
        return file_record

    def _get_human_readable_size(self):
        """获取人类可读的文件大小"""
        self.ensure_one()
        size = self.file_size
        for unit in ['B', 'KB', 'MB', 'GB', 'TB']:
            if size < 1024.0:
                return f"{size:.2f} {unit}"
            size /= 1024.0
        return f"{size:.2f} PB"

